<script lang="ts" setup>
import { ref, watch } from "vue"
import { useTagsViewStore } from "@/store/modules/tags-view"
import { useAppStore } from "@/store/modules/app"
import { getAreaListApi } from "@/api/architecture/index"
import Hamburger from "./Hamburger/index.vue"
import Breadcrumb from "./Breadcrumb/index.vue"
import { ElMessage } from "element-plus"
import { storeToRefs } from "pinia"

interface IPartition {
  label: string
  value: number
}

const appStore = useAppStore()

const tagsViewStore = useTagsViewStore()
const { partition } = storeToRefs(tagsViewStore)
// 分区options
const partitionOptions = ref<IPartition[]>([])

// 获取分区数据
const getPartitionListData = async () => {
  try {
    const params = {
      device_type_id: 1
    }
    const res = await getAreaListApi(params)
    const { data, result, return_message } = res

    if (result === 200) {
      partitionOptions.value = data.data.map((item) => {
        return {
          value: item.id,
          label: item.area_name
        }
      })

      // 默认选择第一个分区
      partition.value = partitionOptions.value[0]?.value ?? ""
    } else {
      ElMessage.error(return_message)
    }
  } catch (error) {
    console.info(error)
  }
}

// 切换侧边栏
const toggleSidebar = () => {
  appStore.toggleSidebar(false)
}

watch(
  () => tagsViewStore.showSelect,
  (status) => {
    status && getPartitionListData()
  },
  {
    immediate: true
  }
)
</script>

<template>
  <section class="app-main" flex flex-col>
    <div flex items-center justify-between bg-white h-60px px-15px>
      <div flex items-center justify-between h-60px>
        <Hamburger :is-active="appStore.sidebar.opened" pr-15px cursor-pointer @toggle-click="toggleSidebar" />
        <Breadcrumb class="breadcrumb" />
      </div>

      <div v-if="tagsViewStore.showSelect">
        <el-select clearable v-model="partition" placeholder="请选择分区" style="width: 185px">
          <el-option v-for="item in partitionOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>
    </div>

    <div class="app-scrollbar">
      <!-- key 采用 route.path 和 route.fullPath 有着不同的效果，大多数时候 path 更通用 -->
      <router-view v-slot="{ Component, route }">
        <transition name="el-fade-in" mode="out-in">
          <keep-alive :include="tagsViewStore.cachedViews">
            <component :is="Component" :key="route.path" class="app-container-grow" />
          </keep-alive>
        </transition>
      </router-view>
    </div>
    <!-- 返回顶部 -->
    <el-backtop />
    <!-- 返回顶部（固定 Header 情况下） -->
    <el-backtop target=".app-scrollbar" />
  </section>
</template>

<style lang="scss" scoped>
@import "@/styles/mixins.scss";

.app-main {
  width: 100%;
  display: flex;
}

.app-scrollbar {
  padding: 30px 20px 20px;
  flex-grow: 1;
  overflow: auto;
  @extend %scrollbar;
  display: flex;
  flex-direction: column;
  .app-container-grow {
    flex-grow: 1;
  }
}
</style>
